import { appliaction, pay} from '../../api/index.js'
import { wxPay} from '../../utils/pay.js'

// pages/train/train.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    trainTime: '',
    trainAdr: '',
    nextBtnText: '下一步',
    payType: false,
    addressList: [
      '西湖',
      '上城',
      '下城',
      '江干',
      '拱墅',
      '滨江',
      '富阳',
      '萧山',
      '余杭']
  },

  onShow: function() {
    console.log(this.data, 'render data')
  },

  navigatePayMethod: function() {
    wx.navigateTo({
      url: '/pages/payMethod/payMethod',
    })
  },

  onTap: function(e) {
    const {addressList} = this.data
    const {detail:{value}, currentTarget:{dataset:{info}}} = e
    console.log(info)
    if (info === 'time') {
      this.setData({
        trainTime: value
      })
    }else {
      this.setData({
        trainAdr: addressList[value]
      })
    }

    console.log(this.data, 'render this data')
  },

  onTapNext: function() {
    const flag = this.valid()

    this.setData({
      nextBtnText: '支付'
    },() => {
      if (flag) {
        this.showModal()
      }
    })
  },

  showModal: function() {
    this.setData({
      payType: true
    })
  },

  hideModal: function () {
    this.setData({
      payType: false,
      nextBtnText: '下一步'
    })
  },

  valid: function() {
    const {trainAdr, trainTime} = this.data

    if(!trainTime) {
      return wx.showToast({
        title: '请选择培训时间',
        icon: 'none'
      })
    }else if(!trainAdr) {
      return wx.showToast({
        title: '请选择培训地点',
        icon: 'none'
      })
    }

    return true
  },

  onSubmit: function() {
    const { trainTime, trainAdr} = this.data

    

    appliaction({ training_time: trainTime, training_address: trainAdr })
      .then(res => {
        // wx.showToast({
        //   title: '申请成功',
        //   icon: 'none'
        // })
        pay({ payment_type: 'training', training_id: res.data.training_id })
          .then(res => {
            console.log(res, '微信支付')
            wxPay(res.data)
            .then(res => {
              cosnole.log(res, '调用支付成功')
            })
            .catch(e => {
              cosnole.log(e, '调用支付')
            })
          })
          .catch(e => {
            console.log(e, '支付')
          })
      })
      .catch(e => {
        console.log(e, '申请培训');
      })
    }
  
})